package utils

import (
	mylog "football/src/log"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

var (
	CalculateData *gorm.DB
	Football      *gorm.DB
)

func Init() {
	InitConfig()
	InitMysql()
}

func InitConfig() {
	viper.SetConfigName("app")
	viper.AddConfigPath("src/config")
	err := viper.ReadInConfig()
	if err != nil {
		Error("Failed to initialize config >>>>>>> ", err)
		panic(err)
	}

	mylog.Info("config app initialized successfully >>>>> ")

}

func InitMysql() {

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)

	var err error
	if CalculateData, err = gorm.Open(mysql.Open(viper.GetString("mysql.calculate_data")), &gorm.Config{
		Logger: newLogger,
	}); err != nil {
		Error("Failed to initialize database connection with mysql on table calculate_data >>>>>", err)
		return
	}

	// Configuration values for the connection pool
	maxIdleConns := 10           // 最大空闲连接数
	maxOpenConns := 25           // 最大打开连接数
	connMaxLifeTime := time.Hour // 连接最大生存时间

	// Set connection pool parameters
	sqlDB, err := CalculateData.DB()
	if err != nil {
		Error("Failed to get database connection from GORM >>>>>>>>>>", err)
		return
	}
	sqlDB.SetMaxIdleConns(maxIdleConns)       // Set max idle connections
	sqlDB.SetMaxOpenConns(maxOpenConns)       // Set max open connections
	sqlDB.SetConnMaxLifetime(connMaxLifeTime) // Set connection max lifetime

	if Football, err = gorm.Open(mysql.Open(viper.GetString("mysql.football")), &gorm.Config{
		Logger: newLogger,
	}); err != nil {
		Error("Failed to initialize database connection with football >>>>>>>>>>", err)
		return
	}

	// Set connection pool parameters for the second database as well
	sqlDB2, err := Football.DB()
	if err != nil {
		Error("Failed to get database connection from GORM >>>>>>>>>>", err)
		return
	}
	sqlDB2.SetMaxIdleConns(maxIdleConns)
	sqlDB2.SetMaxOpenConns(maxOpenConns)
	sqlDB2.SetConnMaxLifetime(connMaxLifeTime)

	mylog.Info("Database connection successfully >>>>>")
}
